<?php

class plgJcommentsAlphauserpointsInstallerScript
{
	function preflight($type, $parent)
	{
		JError::setErrorHandling(E_ALL ^ E_ERROR, 'ignore');
	}

	function postflight($type, $parent)
	{
		jimport('joomla.filesystem.folder');
		jimport('joomla.filesystem.file');

		$rules = JFolder::files(JPATH_SITE.'/plugins/jcomments/alphauserpoints/rules', '\.xml', true, true);
		
		foreach($rules as $rule) {
			$this->installRule($rule);
		}
	}

	function installRule($xmlFile)
	{
		if ($xml = JFactory::getXML($xmlFile)) {
			if ($xml->getName() == 'alphauserpoints') {
				$ruleName = (string) $xml->rule;
				$ruleDescription = (string) $xml->description;
				$component = (string) $xml->component;
				$pluginFunction = (string) $xml->plugin_function;

				$fixedpoints = (string) $xml->fixed_points;
				$fixedpoints = (trim(strtolower($fixedpoints)) == 'true') ? 1 : 0;
				
				if ($ruleName != '' && $ruleDescription != '' && $pluginFunction != '' && $component != '') {
					
					$db = JFactory::getDBO();

					$query = "SELECT COUNT(*) FROM `#__alpha_userpoints_rules` WHERE `plugin_function` = '$pluginFunction'";
					$db->setQuery($query);
					$count = $db->loadResult();

					if (!$count) {
						$query = "INSERT INTO #__alpha_userpoints_rules (`id`, `rule_name`, `rule_description`, `rule_plugin`, `plugin_function`, `component`, `fixedpoints`, `category`, `access`) "
							. " VALUES ('', '$ruleName', '$ruleDescription', '$component', '$pluginFunction', '$component', '$fixedpoints', 'fo', 1);";
						$db->setQuery($query);
						$db->query();
					}
				}
			}
		}		
	}
}